package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.service.IUserService;
import com.itheima.mp.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: UserImpl
 * Package: com.itheima.mp.domain.po.service.impl
 * Description:
 *
 * @Author 那啥啥
 * @Create 2024/1/6  19:39
 * @Version 1.0
 */
@Service
public class UserImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    @Transactional
    public void deductBalance(Long id, Integer money) {
        //查询用户
        User user = this.getById(id);
//        校验用户状态
        if(user == null || user.getStatus() == UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常");
        }
//        校验金额是否充足
        if(user.getBalance()<money){
            throw new RuntimeException("用户余额不足");
        }

        int remainBalance = user.getBalance() - money;
//        扣减余额
//        baseMapper.deductBalance(id,money);
lambdaUpdate()
        .set(User::getBalance,remainBalance)
        .set(remainBalance == 0 ,User::getStatus,UserStatus.FROZEN)
        .eq(User::getId,id)//构建条件
        .eq(User::getBalance,user.getBalance())//加乐观锁
        .update();//执行
    }

    @Override
    public List<User> queryUsers(String name, Integer minBalance, Integer maxBalance, Integer status) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO queryUsersAndAddressById(Long id) {
        //查询用户
        User user = getById(id);
        if(user == null || user.getStatus() == UserStatus.FROZEN){
            throw  new RuntimeException("用户状态异常");
        }

        //查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();

       //封装VO
        //转user为vo
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //转地址为VO属性
        if (CollUtil.isNotEmpty(addresses)){

          userVO.setAddresses(BeanUtil.copyToList(addresses,AddressVO.class));
        }
        return userVO;

    }

    @Override
    public List<UserVO> queryUserByIds(List<Long> ids) {
        //查询用户
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)){
            return Collections.emptyList();
        }

        //查询地址

        //获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //根据id集合查询
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
    //地址转VO
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        Map<Long, List<AddressVO>> addressMap = new HashMap<>(0);
        //梳理地址集合分组处理，相同用户的放入一个集合中
        if(CollUtil.isNotEmpty(addressVOS)){

           addressMap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));//按照用户id分组为一个map集合
        }



//        转VO返回
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user: users) {
            //将User 的PO转为VO
            UserVO vo = BeanUtil.copyProperties(user, UserVO.class);

            list.add(vo);
            //转换地址VO
            vo.setAddresses(addressMap.get(user.getId()));
        }
        return list;
    }
}
